package org.lfh.wintersun.utils.redis;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class SingleLock implements Lock {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean tryLock(String key, String threadId) {
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, threadId, 30, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);
    }

    @Override
    public void unlock(String key, String threadId) {
        //TODO 原子性 LUA
        String curThreadId = redisTemplate.opsForValue().get(key);
        if (Objects.equals(curThreadId, threadId)) {
            redisTemplate.delete(key);
        }
    }
}
